package com.yiba.vpn.service;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import com.yiba.vpn.config.ResultStatus;
import com.yiba.vpn.domain.Wallet;
import com.yiba.vpn.dto.WalletDto;
import com.yiba.vpn.model.ResultModel;
import com.yiba.vpn.repository.WalletRepository;
import com.yiba.vpn.util.RegexUtil;

/** 
 * 钱包业务类
* @author : tang 
* @createtime ：2018年2月7日 上午11:31:58 
* 
*/
@Service
public class WalletService {
	
	 private static Logger logger = Logger.getLogger(WalletService.class);

	 @Autowired
	 private WalletRepository walletRepository;

	/**
	 * 检验并保存用户上传的钱包  , 不含修改操作
	 * @param walletDto
	 * @return
	 */
	public ResponseEntity<ResultModel> save(WalletDto walletDto) {
		String walletStr = walletDto.getWallet();
		if (!RegexUtil.isWallet(walletStr)) {
			return new ResponseEntity<ResultModel>(ResultModel.error(ResultStatus.NOT_WALLET), HttpStatus.OK);
		}
		
		Wallet wallet = null;
		String account = walletDto.getAccount();
		try {
			wallet = walletRepository.findByAccount(account);
		} catch (Exception e) {
			logger.error("保存钱包时查询当前用户的钱包信息异常" + e);
		}
		
		// wallet 不为空 ，当前用户在库里已经有了钱包 ，不做修改，驳回
		if (wallet != null) {
			return new ResponseEntity<ResultModel>(ResultModel.error(ResultStatus.WALLET_HAD_EXIST), HttpStatus.OK);
		}
		wallet = new Wallet();
		wallet.setAccount(account);
		wallet.setWallet(walletStr);
		try {
			wallet = walletRepository.save(wallet);
		} catch (Exception e) {
			logger.error("存储重复钱包" + e);
			return new ResponseEntity<ResultModel>(ResultModel.error(ResultStatus.WALLET_HAD_EXIST), HttpStatus.OK);
		}
		return new ResponseEntity<ResultModel>(ResultModel.ok(), HttpStatus.OK);
	}
	
	/**
	 * 查询当前用户的钱包
	 * @param account
	 * @return
	 */
	public String getWallet(String account) {
		String result = null;
		try {
			 Wallet wallet = walletRepository.findByAccount(account);
			 if (wallet != null) {
				result = wallet.getWallet(); 
			 }
		} catch (Exception e) {
			logger.error("返回wfeeinfo时查询当前用户的钱包信息异常" + e);
		}
		return result;
	}
	 
	 
	 
}
 